/*
 * @Author: DUST
 * @Date: 2023-05-16 13:55:11
 * @LastEditors: DUST
 * @LastEditTime: 2023-11-26 14:40:02
 * @FilePath: \business-card-system\admin\src\utils\index.ts
 * @Description:
 * undefined
 */
import { RouteMenuInterface } from "@/interface";
import { Method } from "axios";

/**
 * @description: 根据输入ip改变是否带上证书
 * @param {string} address：地址
 * @param {*} type: 协议类型
 * @return {*} 返回识别后的地址
 */
export const changeProtocol = (address: string, type: "http" | "ws") => {
  const res = parseInt(address);
  const flag = isNaN(res);
  switch (type) {
    case "http":
      return flag ? `https` : `http`;
    case "ws":
      return flag ? `wss` : `ws`;
  }
};

/**
 * 通过key查询这个key下的路由
 * @param key 当前key
 */
export const FindChildrenFromRoute = (
  key: string | unknown,
  MyroutesArr: RouteMenuInterface[]
): RouteMenuInterface[] | undefined => {
  console.log("key:", key);
  let children;
  for (const item of MyroutesArr) {
    if (item.meta && item.meta.key == key) {
      children = item.children;
    }
  }
  return children;
};

/**
 * @description: 获取随机十六进制颜色
 */
export const color16 = () => {
  //十六进制颜色随机
  const r = Math.floor(Math.random() * 255);
  const g = Math.floor(Math.random() * 255);
  const b = Math.floor(Math.random() * 255);
  const color = `rgba(${r}, ${g}, ${b}, 0.7)`;
  // const color = `#${r.toString(16).padStart(2, "0")}${g
  //   .toString(16)
  //   .padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
  // console.log(color);
  return color;
};

export const tagsPresetsColor = () => {
  const arr = ["pink", "red", "orange", "green", "cyan", "blue", "purple"];

  const index = Math.ceil(Math.random() * arr.length);
  if (index > arr.length - 1) return arr[index - 1];
  return arr[index];
};

export function getStrOrigin(val: string) {
  let text = "";
  if (val && typeof val === "string") {
    const reg = /((https|http|ftp|file):\/\/)([A-Za-z0-9\-.]+)(:[0-9]+){0,1}/g;
    const arr = val.match(reg);
    if (arr && arr.length > 0) {
      text = arr[0];
    }
  }
  return text;
}
/**
 * post params转formdata
 * post自动检查文件,如果有文件,直接转formdata
 * @param params 参数集合
 * @param method 请求方法
 */
export const ParamsToFormData = (
  params: { [text: string]: string | File | File[] },
  method?: Method
) => {
  let formdata = null;
  if (
    method &&
    ["post", "POST", "put", "PUT"].includes(method) &&
    params instanceof FormData == false &&
    params instanceof Object
  ) {
    const values = Object.values(params);
    console.log("canshu");
    if (
      values.filter(
        (item) =>
          item instanceof File ||
          (Object.prototype.toString.call(item) == "[object Array]" &&
            item.length &&
            item[0] instanceof File)
      ).length > 0
    ) {
      formdata = new FormData();
      for (const key in params) {
        if (Object.prototype.hasOwnProperty.call(params, key)) {
          const value = params[key];
          if (value != undefined && value != "undefined") {
            console.log(key, Object.prototype.toString.call(value));
            if (Object.prototype.toString.call(value) == "[object Array]") {
              for (let i = 0; i < value.length; i++) {
                const element = value[i];
                formdata.append(key, element);
              }
            } else {
              formdata.append(key, value);
            }
          }
        }
      }
    }
  }
  return formdata ? formdata : params;
};

/**
 *
 * @param url 需要转换的图片地址
 * @param cb 回调方法
 */
//图片地址转base64格式
export const imgToBase64 = (url: string, cb: (base: string) => void) => {
  let canvas: any = document.createElement("canvas");
  const ctx: any = canvas.getContext("2d"),
    img = new Image();

  img.setAttribute("crossOrigin", "anonymous");
  img.onload = function () {
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0);
    const dataURL = canvas.toDataURL("image/png");
    cb && cb(dataURL);
    canvas = null;
  };
  img.src = url;
};
/**
 *
 * @param base 图片base64地址
 * @param filename 文件名
 */
//base64转file对象
export const base64toFile = (base: any, filename: string) => {
  const arr = base.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const suffix = mime.split("/")[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  //转换成file对象
  return new File([u8arr], `${filename}.${suffix}`, { type: mime });
};
